import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/smoking_record.dart';

class StorageService {
  static const String _recordsKey = 'smoking_records';
  
  // 保存记录列表
  Future<void> saveRecords(List<SmokingRecord> records) async {
    final prefs = await SharedPreferences.getInstance();
    final jsonList = records.map((record) => record.toJson()).toList();
    await prefs.setString(_recordsKey, jsonEncode(jsonList));
  }
  
  // 加载记录列表
  Future<List<SmokingRecord>> loadRecords() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = prefs.getString(_recordsKey);
    
    if (jsonString == null || jsonString.isEmpty) {
      return [];
    }
    
    final jsonList = jsonDecode(jsonString) as List;
    return jsonList
        .map((json) => SmokingRecord.fromJson(json))
        .toList();
  }
  
  // 添加一条记录
  Future<List<SmokingRecord>> addRecord(SmokingRecord record) async {
    final records = await loadRecords();
    records.add(record);
    await saveRecords(records);
    return records;
  }
  
  // 获取特定日期的记录
  Future<List<SmokingRecord>> getRecordsForDate(DateTime date) async {
    final allRecords = await loadRecords();
    return allRecords.where((record) => record.isSameDay(date)).toList();
  }
  
  // 获取按日期分组的记录计数
  Future<Map<DateTime, int>> getRecordCountsByDate() async {
    final allRecords = await loadRecords();
    final Map<DateTime, int> countMap = {};
    
    for (final record in allRecords) {
      final date = DateTime(
        record.timestamp.year,
        record.timestamp.month,
        record.timestamp.day,
      );
      
      countMap[date] = (countMap[date] ?? 0) + 1;
    }
    
    return countMap;
  }
} 